(function (window) {
    'use strict';

    // Your starting point. Enjoy the ride!

    var filters = {
		all: function (todos) {
			return todos;
		},
		active: function (todos) {
			return todos.filter(function (todo) {
				return !todo.completed;
			});
		},
		completed: function (todos) {
			return todos.filter(function (todo) {
				return todo.completed;
			});
		}
	};

    new Vue({
        el: '.todoapp',
        data: {
            todolist: [],
            newTodo: ''
        },
        computed: {
	        filteredTodos: function () {
				return filters[this.visibility](this.todolist);
			},
			remaining: function () {
				return filters.active(this.todolist).length;
			},
			remainingText: function () {
				if (this.remaining === 0 || this.remaining > 1) {
					return this.remaining + ' items';
				} else {
					return this.remaining + ' item';
				}
			},
			allDone: {
				get: function () {
					return this.remaining === 0;
				},
				set: function (value) {
					this.todolist.forEach(function (todo) {
						todo.completed = value;
					});
				}
			}
	    },
        methods: {
            addTodo: function () {
                if (this.newTodo) {
                    var todo = this.newTodo.trim();
                    this.todolist.push({label: todo, completed: false, editing: false});
                    this.newTodo = '';
                }
            },
            removeTodo: function (todo) {
	            this.todolist.$remove(todo);
            },
            editTodo: function (todo) {
	            this.editingTodoOldValue = todo.label;
	            todo.editing = true;
            },
            finishEdit: function (todo) {
	            if (!todo.editing) {
		            return;
	            }
	            todo.editing = false;
				todo.label = todo.label.trim();
				if (!todo.label) {
					this.removeTodo(todo);
				}
            },
            cancelEdit: function (todo) {
	            todo.editing = false;
				todo.label = this.editingTodoOldValue;
            },
            removeCompleted: function () {
				this.todolist = filters.active(this.todolist);
			}
        },
        directives: {
			'auto-focus': function (value) {
				if (!value) {
					return;
				}
				var el = this.el;
				Vue.nextTick(function () {
					el.focus();
				});
			}
		}
    });

})(window);
